<template>
  <div class="update-avatar">
    <img :src="img" id="image" />
    <div class="toolbar">
      <span @click="$emit('close')">取消</span>
      <span @click="onConfirm">完成</span>
    </div>
  </div>
</template>

<script>
import { editUserAvatar } from '@/api/user.js'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
  props: {
    // 用户选择的img
    img: {
      type: String,
      required: true
    },
    // 后台的img头像
    value: {
      type: String,
      required: true
    }
  },
  mounted () {
    const image = document.getElementById('image')
    this.cropper = new Cropper(image, {
      viewMode: 1, // 只能在裁剪的图片范围内移动
      dragMode: 'move', // 画布和图片都可以移动
      aspectRatio: 1, // 裁剪区默认正方形
      autoCropArea: 1, // 自动调整裁剪图片
      cropBoxMovable: false, // 禁止裁剪区移动
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false // 关闭默认背景
    })
    console.log(this)
  },
  methods: {
    onConfirm () {
      try {
        this.cropper.getCroppedCanvas().toBlob(async blob => {
          const formData = new FormData()
          formData.append('photo', blob)
          const { data } = await editUserAvatar(formData)
          console.log(data)
          this.$toast.success('更新头像成功')
          this.$emit('close')
          this.$emit('input', data.data.photo)
        })
      } catch (err) {
        this.$toast.success('更新失败,请稍后再试')
      }
    },
    save () {
      // 数据交给后台,让服务器裁剪
      // console.log(this.cropper.getData())
      // 客服端裁剪
      // 通过getCroppedCanvas()方法得到一个canvas元素,再通过canvas的toBlob方法转化为二进制对象
      this.cropper.getCroppedCanvas().toBlob(blob => {
        console.log(blob)
      })
    }
  }
}
</script>

<style scoped lang='less'>
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 35px 20px;
    box-sizing: border-box;
  }
}
</style>
